package com.shiwaixiangcun.customer.module.ticket

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.CommonObjCallBack
import com.shiwaixiangcun.customer.entity.SiteDetail
import com.shiwaixiangcun.customer.entity.TicketOrderDetail
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.ArithmeticUtils
import com.shiwaixiangcun.customer.utils.DateUtil
import kotlinx.android.synthetic.main.activity_ticket.*
import kotlinx.android.synthetic.main.activity_ticket_detail.*
import kotlinx.android.synthetic.main.layout_ticket_detail.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 车票详情页面
 */
class TicketDetailActivity : BaseActivity() {
    var ticketOrderId: String? = null
    var orderNumber: String? = null
    var ticketStatus: String? = null
    val UPDATE_UI = 1
    var isFromItem: Boolean = false
    var siteInfoList: MutableList<SiteDetail>? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ticket_detail)
        ticketOrderId = intent.extras.getString("ticketOrderId")
        isFromItem = intent.extras.getBoolean("fromItem")
        orderNumber = intent.extras.getString("number")
        ticketStatus = intent.extras.getString("ticketStatus")
        EventUtil.getInstance().register(this)

        initViewAndEvent()
        initData()
    }

    private fun initViewAndEvent() {

        tv_page_name.text = "车票详情"
        back_left.setOnClickListener { finish() }
        siteInfoList = ArrayList()


        when (ticketStatus) {
            "Checked" -> {
                layout_code.visibility = View.GONE
                layout_ticket_status.visibility = View.VISIBLE
                tv_status.text = "已使用"
                tv_status_info.text = "车票通过验证,祝你乘车愉快"
            }
            "Wait_Check" -> {
                layout_code.visibility = View.VISIBLE
                layout_ticket_status.visibility = View.GONE

            }
            "Refund" -> {
                layout_code.visibility = View.GONE
                layout_ticket_status.visibility = View.VISIBLE
                tv_status.text = "已退票"
                tv_status_info.text = "您的车票已完成退票，谢谢"
            }
            else -> {
                layout_ticket_status.visibility = View.GONE
            }
        }

        if (isFromItem) {
            layout_success.visibility = View.GONE

        } else {
            layout_code.visibility = View.VISIBLE
            layout_success.visibility = View.VISIBLE
        }

        layout_site.setOnClickListener {
            if (siteInfoList?.size == 0) {
                showToastShort("暂无图片信息")
            } else {
                val bundle = Bundle()
                bundle.putParcelableArrayList("siteInfo", siteInfoList as ArrayList<SiteDetail>)
                readyGo(SiteInfoActivity::class.java, bundle)
            }
        }

    }

    private fun initData() {

        val strToken = AppSharePreferenceMgr.get(mContext, GlobalConfig.TOKEN, "") as String

        OkGo.get<String>(GlobalApi.ticketOrderDetail)
                .params("access_token", strToken)
                .params("orderId", ticketOrderId)
                .params("number", orderNumber)
                .execute(object : StringCallback() {

                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        showToastShort("请求数据失败")
                    }

                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<CommonObjCallBack<TicketOrderDetail>>() {}.type
                        val responseEntity = Gson().fromJson<CommonObjCallBack<TicketOrderDetail>>(response?.body(), type)
                        when (responseEntity.responseCode) {
                            1001 -> {
                                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.UPDATE_TICKET_ORDER_DETAIL, UPDATE_UI, responseEntity.data))

                            }
                            else -> {
                                showToastShort("请求数据失败")
                            }


                        }
                    }

                })

    }

    override fun onDestroy() {
        EventUtil.getInstance().unregister(this)
        super.onDestroy()
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(event: SimpleEvent) {
        if (event.mEventType != SimpleEvent.UPDATE_TICKET_ORDER_DETAIL || event.mEventValue != UPDATE_UI) {
            return
        }
        val ticketDetail = event.data as TicketOrderDetail

        tv_start_time.text = DateUtil.getCustomFormat(ticketDetail.rideTime, "yyyy-MM-dd  HH:mm")
        tv_start.text = ticketDetail.startSite
        tv_end.text = ticketDetail.endSite
        tv_ticket_info.text = ticketDetail.survey
        tv_origin.text = ticketDetail.startLocation
        tv_destination.text = ticketDetail.endLocation
        tv_passenger_name.text = ticketDetail.buyer
        tv_passenger_phone.text = ticketDetail.phone
        tv_order_time.text = DateUtil.getSecond(ticketDetail.orderTime)
        tv_payway.text = ticketDetail.payWay
        tv_order_total.text = "￥${ArithmeticUtils.format(ticketDetail.totalPrice)}"
        tv_amount.text = "共${ticketDetail.count}张"
        val siteInfo = StringBuilder()
        ticketDetail.searNumber.map {
            siteInfo.append("${it}座、")
        }
        tv_site_number.text = siteInfo.dropLast(1)


        val length = ticketDetail.code.length
        val position = length / 2
        val codeInfo = StringBuilder()
        ticketDetail.code.forEachIndexed { index, c ->
            if (index == position) {
                codeInfo.append("  ")
            }
            codeInfo.append(c)
        }
        tv_code.text = codeInfo

        ticketDetail.endSiteImages.map {
            val siteInfo = SiteDetail("下车地址", it.path, it.address)
            siteInfoList!!.add(siteInfo)
        }
        ticketDetail.startSiteImages.map {
            val siteInfo = SiteDetail("上车地址", it.path, it.address)
            siteInfoList!!.add(siteInfo)
        }


    }
}
